
using API.Middlewares;
using AutoMapper;
using DTO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using Newtonsoft.Json;
using SqlSugar;
using Util;

namespace API.Controllers
{
    public class SignInController : BaseController
    {
        Repository<tSignIn> _SignIn;
        Repository<tAutoMealReporting> _auto;
        readonly IMapper _mapper;
        Repository<tFace> _face;
        private readonly IWebSocketManager _webSocketManager;
        Repository<tStaff> _tUser;

        Repository<tMealReporting> _reporting;
        public SignInController(Repository<tSignIn> SignIn, IMapper mapper, Repository<tAutoMealReporting> auto, Repository<tMealReporting> reporting, Repository<tFace> face, IWebSocketManager webSocketManager, Repository<tStaff> tUser)
        {
            _SignIn = SignIn;
            _mapper = mapper;
            _auto = auto;
            _reporting = reporting;
            _face = face;
            _webSocketManager = webSocketManager;
            _tUser = tUser;
        }

        /// <summary>
        /// 获取用户的英文名称
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<string>> GetUserEngName(string userid)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                string EngName = string.Empty;
                var model = await _auto.GetFirstAsync(x => x.FEId == userid);
                if (model != null)
                {
                    EngName = model.FEEngName;
                }
                return result.Success(EngName);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("SignInController-GetUserEngName:" + ex.ToString());
                return result.Exception();
            }
        }


        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> Save([FromBody] SaveSignInInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = _mapper.Map<tSignIn>(dto);
                InitEntity(model);
                await _SignIn.InsertOrUpdateAsync(model);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("SignInController--Save:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<SignInOutput>>> GetList([FromBody] SignInListInput dto)
        {
            ResultMsg<List<SignInOutput>> result = new ResultMsg<List<SignInOutput>>();
            try
            {
                if (dto.PageNum <= 0)
                {
                    return result.Error("PageNum不能小于或等于0");
                }
                if (dto.PageSize <= 0)
                {
                    return result.Error("PageSize不能小于或等于0");
                }
                SqlSugar.PageModel pageModel = new SqlSugar.PageModel
                {
                    PageIndex = dto.PageNum,
                    PageSize = dto.PageSize,
                };
                var exp = Expressionable.Create<tSignIn>();
                //if (!string.IsNullOrWhiteSpace(dto.Name))
                //{
                //    exp.And(x => x.FName.Contains(dto.Name));
                //}
                var list = (await _SignIn.GetPageListAsync(exp.ToExpression(), pageModel)).OrderByDescending(x => x.CreateTime).ToList();
                var SignInOutputs = _mapper.Map<List<SignInOutput>>(list);
                return result.Success(SignInOutputs, pageModel.TotalCount);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("SignInController--GetList:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 获取唯一
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<SignInOutput>> GetTheOne(string id)
        {
            ResultMsg<SignInOutput> result = new ResultMsg<SignInOutput>();
            try
            {
                var model = await _SignIn.GetByIdAsync(id);
                var dao = _mapper.Map<SignInOutput>(model);
                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("SignInController--GetTheOne:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<string>> Del(string id)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                await _SignIn.DeleteByIdAsync(id);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("SignInController--Del:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 根据UserID进行一系列数据的清除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ResultMsg<string> UpdateByUserId([FromBody] List<UpdateByUserIdInput> list)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                if (list.Count == 0)
                {
                    return result.Error("请传入userid");
                }
                //自动报餐数据清除
                var autoList = _auto.GetList(x => list.Select(x => x.userID).Contains(x.FEId));
                if (autoList.Count > 0)
                {
                    foreach (var item in autoList)
                    {
                        var model = list.Where(x => x.userID == item.FEId).FirstOrDefault();
                        if (model.Disable)
                        {
                            _auto.Delete(item);
                        }
                        else
                        {
                            item.FEName = model.userName;
                            item.FEId = model.userID;
                            item.FEEngName = model.userEname;
                            _auto.Update(item);
                        }
                    }
                }
                //报餐表数据更新
                var repList = _reporting.GetList(x => list.Select(c => c.userID).Contains(x.FEID.ToString()));
                if (repList.Count > 0)
                {
                    foreach (var item in repList)
                    {
                        var model = list.Where(x => x.userID == item.FEID.ToString()).FirstOrDefault();
                        if (model != null)
                        {
                            item.FEName = model.userName;
                            item.FEID = model.userID;
                            item.FEEngName = model.userEname;
                            item.FDeleted = model.Disable;
                            _reporting.Update(item);
                        }
                    }
                }
                //签到表数据更新
                var signList = _SignIn.GetList(x => list.Select(c => c.userID).Contains(x.FEId.ToString()));
                if (signList.Count > 0)
                {
                    foreach (var item in signList)
                    {
                        var model = list.Where(x => x.userID == item.FEId.ToString()).FirstOrDefault();
                        if (model != null)
                        {
                            item.FEName = model.userName;
                            item.FEId = model.userID;
                            item.FEEngName = model.userEname;
                            _SignIn.Update(item);
                        }
                    }
                }

                //人脸数据更新
                var faceList = _face.GetList(x => list.Select(c => c.userID).Contains(x.FUserId.ToString()));
                if (faceList.Count > 0)
                {
                    foreach (var item in faceList)
                    {
                        var model = list.Where(x => x.userID == item.FUserId.ToString()).FirstOrDefault();
                        if (model != null)
                        {
                            if (model.Disable)
                            {
                                item.FDeleted = model.Disable;
                                _face.Update(item);
                                //通过websocket自动删除门禁/食堂设备数据
                                sendFaceDeviceOutput dao = new sendFaceDeviceOutput();
                                //门禁
                                dao.cmd = "to_device";
                                dao.from = "123";
                                dao.to = "QT75031";
                                dao.extra = "";
                                dao.data = new delUserData
                                {
                                    cmd = "delUser",
                                    user_id = item.FUserId,
                                };
                                _webSocketManager.SendToAllAsync(JsonConvert.SerializeObject(dao));

                                dao = new sendFaceDeviceOutput();
                                //食堂
                                dao.cmd = "to_device";
                                dao.from = "123";
                                dao.to = "H70982";
                                dao.extra = "";
                                dao.data = new delUserData
                                {
                                    cmd = "delUser",
                                    user_id = item.FUserId,
                                };
                                _webSocketManager.SendToAllAsync(JsonConvert.SerializeObject(dao));
                            }
                        }
                    }
                }
                //删除用户表
                var userList = _tUser.GetList(x => list.Where(c => c.Disable).Select(c => c.userID).Contains(x.FUserId.ToString()));
                if (userList != null && userList.Count > 0)
                {
                    foreach (var item in userList)
                    {
                        item.FDeleted = true;
                        _tUser.Update(item);
                    }
                }
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("SignInController-ClearByUserId:" + ex.ToString());
                return result.Exception();
            }
        }
    }
}
